<template>
	<view class="y-flex y-flex-1 position-relative" style="background-color: rgba(0,0,0,.2);">
		<yingbing-slider :current="current" ref="slider" circular :data="images" class="position-absolute-cover" @change="handleChange($event.current)">
			<template v-slot="{item, index}">
				<view class="y-flex y-flex-1 position-relative">
					<com-image class="y-flex-1" :style="{
						'margin-bottom': item.top + 'px'
					}" :src="item.tempPath" :tip-color="skinColor.color_white" mode="aspectFit" bg-color="rgba(0,0,0,0)"></com-image>
					<view class="position-absolute left-0 right-0 y-flex" :style="{
						'padding-left': pageMarginGap,
						'padding-right': pageMarginGap,
						'bottom': '240rpx'
					}">
						<view class="y-flex y-row y-align-center">
							<text class="fs-30 fw-bold y-flex-1 lines-3 mr-100" :style="{color: skinColor.color_white}">{{item.title || detail.title}}</text>
							<text class="fs-26 mr-20 ft-italic" :style="{color: skinColor.color_white}">{{index+1}} / {{images.length}}</text>
						</view>
						<com-text class="mt-10" line-height="35" size="26" lines="1" :color="skinColor.color_white" :value="item.subtitle || detail.subtitle" v-if="item.subtitle || detail.subtitle"></com-text>
						<com-text class="mt-10" line-height="35" size="26" lines="5" :color="skinColor.color_white" :value="item.description || detail.description" v-if="item.description || detail.description"></com-text>
						<scroll-view class="y-flex y-row y-align-center mt-10" :show-scrollbar="false" scroll-x v-if="(item.tags && item.tags.length > 0) || (detail.tags && detail.tags.length > 0)">
							<view class="find_novel_tag mr-20 border-color-fff" v-for="(item, index) in (item.tags && item.tags.length > 0 ? item.tags : detail.tags)" :key="index" @tap="handleTagTap(item)">
								<text class="fs-24 fr-fff">{{item.title}}</text>
							</view>
						</scroll-view>
					</view>
				</view>
			</template>
		</yingbing-slider>
		<view class="position-absolute bottom-0 left-0 right-0 y-flex">
			<view class="y-flex y-row y-align-center y-justify-between pt-40 pb-40 pl-60 pr-60">
				<com-icon :name="autoplay ? 'stop' : 'play_fill'" :color="skinColor.color_white" size="40" @click="switchAutoplay"></com-icon>
				<com-icon name="album" :color="skinColor.color_white" size="40" @click="actionShow = true"></com-icon>
				<com-icon name="forward" :color="skinColor.color_white" size="40" @click="handleShare"></com-icon>
				<com-icon name="attention" :color="skinColor.color_white" size="40" @click="handlePreview"></com-icon>
			</view>
			<view class="y-flex y-row y-align-center y-justify-center mb-40 opac-6" v-if="components.length > 0 || cell" @tap="handleShowModal">
				<com-icon name="fold" size="24" :color="skinColor.color_white"></com-icon>
				<text class="fs-20 ml-10" :style="{color: skinColor.color_white}">点击查看更多</text>
			</view>
			<com-safe-bottom></com-safe-bottom>
		</view>
		<com-popup position="absolute" :visible.sync="modalShow" direction="bottom" @hide="handleModalHide">
			<view class="y-flex" :style="{'background-color': skinColor.color_bg_1, 'height': modalHeight + 'px'}">
				<module-list
				ref="list"
				:params="modalParams"
				:data="components"
				:cell="cell"
				:bounce="pageStyle.enableBounce"
				:back-top-show="pageStyle.enableBackTop"
				:refreshImage="pageStyle.pulldownRefreshImage"
				:pulldownable="pageStyle.enablePulldown == 1"
				:loadmoreable="pageStyle.enableLoadmore == 1"
				:loadingColor="pageStyle.loadingColor"
				:backTopImage="pageStyle.backTopImage"
				:marginGap="pageStyle.pageMarginGap"
				:showTopGap="components.length == 0"
				@pulldown="handleModalPulldown">
				</module-list>
			</view>
		</com-popup>
		<com-action-sheet :data="action" :visible.sync="actionShow" cancel-show @confirm="handleActionConfirm"></com-action-sheet>
	</view>
</template>

<script>
	import { setWallpaper } from '@/assets/js/native.js'
	import { openDB, closeDB, select, insert, update, remove } from '@/assets/database'
	import ModuleList from './components/ModuleList.vue' 
	export default {
		inject: ['getPage', 'getPageStyle', 'getSkinColor', 'getQuery', 'navigate', 'confirm'],
		components: {ModuleList},
		computed: {
			history () {
				return this.$store.getters['setting/GET_HISTORY']
			},
			skinColor () {
				return this.getSkinColor()
			},
			app () {
				return getApp().globalData
			},
			network () {
				return this.$store.getters['network/GET']
			},
			//获取路由参数
			query () {
				return this.getQuery()
			},
			page () {
				return this.getPage()
			},
			pageStyle () {
				return this.getPageStyle()
			},
			//页面左右边距
			pageMarginGap () {
				return this.app.$utils.pixelunit(this.pageStyle?.pageMarginGap)
			},
			cell () {
				return this.page?.comments || this.page?.cell || null
			},
			components () {
				return this.page?.components || []
			}
		},
		data () {
			return {
				autoplay: false,//自动播放
				detail: {},//详情信息
				images: [],//图片集合
				showComment: false,//显示评论列表
				record: {},//历史记录
				current: 0,
				actionShow: false,//显示操作列表
				action: ['保存至相册', '设为桌面壁纸', '设为锁屏壁纸', '设为桌面和锁屏壁纸'],//操作列表
				modalShow: false,//更多模块展示
				modalHeight: 0,
				modalParams: {}
			}
		},
		mounted () {
			this.$nextTick(this.handlePulldown)
		},
		beforeDestroy() {
			this.stopAutoplay()
		},
		methods: {
			onBackPress () {
				if ( this.actionShow ) {
					this.actionShow = false
					return true
				}
				if ( this.modalShow ) {
					this.modalShow = false
					return true
				}
				if ( this.detail.uniqueId ) {
					if ( this.history == 0 ) {
						this.confirm({
							title: '记录提示',
							content: '当前看到' + (this.current + 1) + '/' + this.images.length + '位置\n\n是否记录',
							cancelText: '取消记录',
							confirmText: '保存记录',
							success: res => {
								if ( res.confirm ) {
									this.saveRecord()
								} else {
									this.app.$Router.back()
								}
							}
						})
					} else if ( this.history == 1 ) this.saveRecord()
					else this.app.$Router.back()
					return true
				}
				return false
			},
			async saveRecord () {
				try{
					await openDB()
					if ( this.record.id ) {
						await update('record', {
							url: this.detail.url,
							title: this.detail.title || '',
							cover: this.detail.cover || '',
							current: this.current,
							current_title: (this.current + 1) + '/' + this.images.length,
							is_adult: this.detail.isAdult,
							source_id: this.detail.sourceId
						}, 'id = ' + this.record.id)
					} else {
						await insert('record', {
							unique_id: this.detail.uniqueId,
							url: this.detail.url,
							title: this.detail.title || '',
							cover: this.detail.cover || '',
							current: this.current,
							current_title: (this.current + 1) + '/' + this.images.length,
							is_adult: this.detail.isAdult,
							source_id: this.detail.sourceId
						})
					}
					closeDB()
					this.app.$Router.back()
				}catch(e){
					closeDB()
					uni.showToast({
						title: e.message,
						icon: 'none'
					})
					setTimeout(() => {
						this.app.$Router.back()
					}, 500)
				}
			},
			onShow () {
				if ( this.detail.uniqueId ) this.getRecord()
				if ( this.images.length > 1 ) {
					this.autoplay = true
					this.startAutoplay()
				}
			},
			onHide () {
				this.autoplay = false
				this.stopAutoplay()
			},
			async getRecord () {
				try{
					await openDB()
					const data1 = await select('record', 'unique_id = "' + this.detail.uniqueId + '"')
					this.record = data1.list[0] || {}
					if ( this.images.length > 0 ) this.handleChange(this.record.current || 0)
					const data2 = await select('collection', 'unique_id = "' + this.detail.uniqueId + '"')
					const utils = [{
						label: data2.count > 0 ? '已收藏' : '点击收藏',
						icon: data2.count > 0 ? 'favor_fill' : 'favor',
						color: data2.count > 0 ? this.skinColor.color_red : '',
						func: async () => {
							try{
								await openDB()
								if ( data2.count > 0 ) {
									await remove('collection', 'id = ' + data2.list[0].id)
									uni.showToast({
										title: '取消收藏成功',
										icon: 'none'
									})
									await closeDB()
									this.getRecord()
								} else {
									const params = {
										unique_id: this.detail.uniqueId,
										url: this.detail.url,
										title: this.detail.title || '',
										cover: this.detail.cover || '',
										is_adult: this.detail.isAdult || 0,
										source_id: this.detail.sourceId
									}
									await insert('collection', params)
									uni.showToast({
										title: '收藏成功',
										icon: 'none'
									})
									await closeDB()
									this.getRecord()
								}
							}catch(e){
								closeDB()
								uni.showToast({
									title: e.message,
									icon: 'none'
								})
							}
						}
					}]
					if ( this.detail.shareUrl && this.detail.title ) {
						utils.push({
							label: '分享资源',
							icon: 'forward',
							func: () => {
								this.app.$Router.push({
									path: '/pages/find/modules/poster',
									animationType: 'none',
									query: {
										params: this.detail
									}
								})
							}
						})
					}
					this.$emit('utils', utils)
				}catch(e){
					uni.showToast({
						title: e.message,
						icon: 'none'
					})
				}
				closeDB()
			},
			handlePreview () {
				const img = this.images[this.current]
				uni.previewImage({ urls: [img.tempPath || img.src] })
			},
			handleActionConfirm (e) {
				const img = this.images[this.current]
				if ( !img.tempPath ) {
					uni.showToast({
						title: '请等待图片加载',
						icon: 'none'
					})
					return
				}
				if ( e.current == 0 ) {
					uni.saveImageToPhotosAlbum({
						filePath: img.tempPath,
						success: () => {
							uni.showToast({
								title: '已保存到相册',
								icon: 'none'
							})
						},
						fail: () => {
							uni.showToast({
								title: '保存到相册失败',
								icon: 'none'
							})
						}
					});
				} else {
					uni.showLoading({ title: '壁纸设置中' })
					setWallpaper(e.current == 1 ? 'wallpaper' : e.index == 2 ? 'lock' : 'all', img.tempPath)
					uni.hideLoading()
				}
			},
			handleShare () {
				const img = this.images[this.current]
				if ( !img.tempPath ) {
					uni.showToast({
						title: '请等待图片加载',
						icon: 'none'
					})
					return
				}
				uni.saveFile({
				  tempFilePath: img.tempPath,
				  success: (res) => {
				    this.app.$utils.shareFile(res.savedFilePath)
				  }
				});
			},
			async handleChange (current) {
				this.stopAutoplay()
				this.current = parseInt(current)
				let img = this.images[current]
				if ( !img.src && !img.loading ) {
					this.$set(this.images[current], 'loading', true)
					const newImg = await this.handleGetContext(img)
					this.$set(this.images[current], 'loading', false)
					this.$set(this.images, current, newImg)
					img = this.images[current]
				}
				if ( !img.tempPath && img.src ) {
					uni.getImageInfo({
						src: img.src,
						success: res => {
							const rate = uni.getSystemInfoSync().windowWidth / res.width
							const realHeight = rate * res.height
							const windowHeight = uni.getSystemInfoSync().windowHeight
							const top = realHeight < windowHeight *  (2 / 3) ? uni.getSystemInfoSync().windowHeight / 4 : 0
							this.$set(this.images[current], 'tempPath', res.path)
							this.$set(this.images[current], 'top', top)
						}
					})
				}
				if ( this.autoplay ) this.startAutoplay()
			},
			async handlePulldown (callback) {
				try{
					this.detail = await this.handleGetDetail()
					this.images = await this.handleGetImages()
					if ( this.detail.uniqueId ) this.getRecord()
					this.$emit('loaded', true)
				}catch(e){
					this.$emit('loaded', true)
				}
			},
			async handleGetDetail () {
				const detail = this.page?.detail || {}
				const staticData = this.network.staticDataHandle(detail.staticData || {}, this.query)
				const dynamicData = detail.dynamicData
				const request = detail.request
				let data = {}
				if ( dynamicData && request ) {
					const newRequest = this.network.requestHandle(request, this.query)
					const response = await this.network.$request(newRequest)
					data = await this.network.$list(dynamicData, response)
					data.uniqueId = data.id || this.network.getUniqueId(newRequest)
					if ( !data.shareUrl && !staticData.shareUrl ) data.shareUrl = await this.network.getShareUrl(newRequest)
				}
				return Object.assign({}, staticData, data)
			},
			async handleGetImages () {
				const items = this.page?.items || {}
				const params = Object.assign({}, this.query, this.detail)
				const staticData = items.staticData ? this.network.staticDataHandle(items.staticData, params) : []
				const dynamicData = items.dynamicData
				const request = items.request
				let data = []
				if ( dynamicData && request ) {
					const newRequest = this.network.requestHandle(request, params)
					const response = await this.network.$request(newRequest)
					data = await this.network.$list(dynamicData, response)
				}
				return staticData.concat(data).map(s => Object.assign({}, s, { loading: false }))
			},
			async handleGetContext (item) {
				const context = this.page?.context || {}
				const request = context.request
				const params = Object.assign({}, this.query, this.detail, item)
				const staticData = context.staticData ? this.network.staticDataHandle(context.staticData, params) : {}
				const dynamicData = context.dynamicData || {}
				const newRequest = request ? this.network.requestHandle(request, params) : null
				const response = newRequest ? await this.network.$request(newRequest) : null
				const data = response ? await this.network.$list(dynamicData, response) : null
				return Object.assign({}, item, staticData, data)
			},
			handleTagTap (item) {
				this.navigate(item.url)
			},
			handleShowModal () {
				const system = uni.getSystemInfoSync()
				this.modalHeight = system.windowHeight - uni.upx2px(100) - system.safeArea.top
				this.modalShow = true
				this.$emit('scroll', 200)
				this.$nextTick(function () {
					this.handleModalPulldown()
				})
			},
			handleModalHide () {
				this.modalShow = false
				this.$emit('scroll', 0)
			},
			handleModalPulldown (callback) {
				this.modalParams = Object.assign({}, this.query, this.detail)
				this.$refs.list && this.$refs.list.initModule(callback, callback ? true : false)
			},
			switchAutoplay () {
				if ( this.images.length < 2 ) {
					uni.showToast({
						title: '只有图片数量大于1的时候才能开启自动播放',
						icon: 'none'
					})
					return
				}
				this.autoplay = !this.autoplay
				if ( this.autoplay ) this.startAutoplay()
				else this.stopAutoplay()
			},
			startAutoplay () {
				this.stopAutoplay()
				this.autoplayTimer = setTimeout(() => {
					if ( this.autoplay ) this.$refs.slider && this.$refs.slider.slideToNext()
					else this.stopAutoplay()
				}, 5000)
			},
			stopAutoplay () {
				if ( this.autoplayTimer ) {
					clearTimeout(this.autoplayTimer)
					this.autoplayTimer = null
				}
			}
		}
	}
</script>

<style>
	.find_novel_tag {
		border-width: 1px;
		border-style: solid;
		border-radius: 5rpx;
		padding: 4rpx 10rpx;
	}
</style>